//
//  LCMusicDataBase.m
//  FMDBDemo
//
//  Created by Zeno on 16/5/18.
//  Copyright © 2016年 zenoV. All rights reserved.
//

#import "LCMusicDataBase.h"
#import "FMDB.h"
#import "Person.h"

static LCMusicDataBase *_LCDBCtl = nil;

@interface LCMusicDataBase()<NSCopying,NSMutableCopying>{
    FMDatabase  *_db;
    
}

@end

@implementation LCMusicDataBase

+(instancetype)sharedDataBase{
    if (_LCDBCtl == nil) {
        _LCDBCtl = [[LCMusicDataBase alloc] init];
        [_LCDBCtl initDataBase];
    }
    return _LCDBCtl;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    if (_LCDBCtl == nil) {
        _LCDBCtl = [super allocWithZone:zone];
    }
    return _LCDBCtl;
}
-(id)copy{
    return self;
}
-(id)mutableCopy{
    return self;
}
-(id)copyWithZone:(NSZone *)zone{
    return self;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return self;
}
-(void)initDataBase{
    // 获得Documents目录路径
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 文件路径
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"musicsearch.sqlite"];
    // 实例化FMDataBase对象
    _db = [FMDatabase databaseWithPath:filePath];
    [_db open];
    // 初始化数据表
    NSString *personSql = @"CREATE TABLE if not exists 'musicsearch' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,'musicsearch_name' VARCHAR(255)) ";
    [_db executeUpdate:personSql];
    [_db close];
}
#pragma mark - 添加
- (void)addPerson:(Person *)person{
    [_db open];
    //先查询一下插入的数据之前有没有
    NSString *query = [NSString stringWithFormat:@"select * from musicsearch where musicsearch_name= '%@'", person.name];
    FMResultSet *rs1 = [_db executeQuery:query];
    while ([rs1 next]) {
//      NSLog(@"111");
//        [_db close];
//        return;//不添加重复的
        [_db executeUpdate:@"DELETE FROM musicsearch WHERE musicsearch_name = ?",person.name];//删除再添加
    }
     //添加数据
    BOOL result = [_db executeUpdate:@"INSERT INTO musicsearch(musicsearch_name)VALUES(?)",person.name];
    NSLog(@"result = %d", result);
    [_db close];
}
#pragma mark - 删除
- (void)deletePerson:(Person *)person{
    [_db open];
    [_db executeUpdate:@"DELETE FROM musicsearch WHERE musicsearch_name = ?",person.name];
    [_db close];
}
#pragma mark - 更新
- (void)updatePerson:(Person *)person{
    [_db open];
    [_db executeUpdate:@"UPDATE 'musicsearch' SET musicsearch_name = ?  ",person.name];
    [_db close];
}
#pragma mark - 获取所有的数据
- (NSMutableArray *)getAllPerson{
    [_db open];
    NSMutableArray *dataArray = [[NSMutableArray alloc] init];
    FMResultSet *res = [_db executeQuery:@"SELECT * FROM musicsearch"];
    while ([res next]) {
        Person *person = [[Person alloc] init];
        person.name = [res stringForColumn:@"musicsearch_name"];
        [dataArray addObject:person];
    }
    [_db close];
    return dataArray;
}
@end
